<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="el-icon-document">发起任务</span>
        <el-button style="float: right;" size="mini" type="danger" @click="goBack">关闭</el-button>
      </div>
      <el-tabs tab-position="top" v-model="activeName" @tab-click="handleClick">
        <!--表单信息-->
        <el-tab-pane label="表单信息" name="1">
          <!--初始化流程加载表单信息-->
          <el-col :span="16" :offset="4">
            <div class="test-form">
              <v-form-render :key="new Date().getTime()" ref="vFormRef" :form-json="formConf" :form-data="formData"
                             :option-data="optionData">
              </v-form-render>
              <el-button type="primary" @click="submitForm()">提交</el-button>
              <el-button type="primary" @click="resset()">重置</el-button>
            </div>
          </el-col>
        </el-tab-pane>
        <!--流程图-->
        <el-tab-pane label="流程图" name="2">
          <flow :flowData="flowData"/>
        </el-tab-pane>
      </el-tabs>
      <!--选择流程接收人-->
      <el-dialog :title="taskTitle" :visible.sync="taskOpen" width="65%" append-to-body>
        <flow-user v-if="checkSendUser" :checkType="checkType" @handleUserSelect="handleUserSelect"/>
        <flow-role v-if="checkSendRole" @handleRoleSelect="handleRoleSelect"/>
        <span slot="footer" class="dialog-footer">
          <el-button @click="taskOpen = false">取 消</el-button>
          <el-button type="primary" @click="submitTask">提 交</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import flow from '@/views/admin/task/sendprocess/flow.vue'
import FlowUser from '@/components/flow/User/index.vue'
import FlowRole from '@/components/flow/Role/index.vue'
import {fetchData, deteleData, ExportData, saveorUpadateDate, deteleAllData, saveorUpadateDateParam} from '@/api/index';
import {onMounted, reactive, ref,watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import {useStore} from "vuex";

let flowData = ref({})
let router = useRouter()
let store = useStore()
let activeName = ref('1')
let defaultProps = reactive({
  children: "children",
  label: "label"
})
let queryParams = reactive({
  deptId: undefined
})
let route: any = useRoute()
let optionData = reactive({})
let loading = ref(true)
let deployId = ref("")
let procDefId = ref("")
let formConf = ref({})
let variables = reactive([])
let taskTitle = ref("")
let taskOpen = ref(false)
let checkSendUser = ref(false)
let checkSendRole = ref(false)
let checkType = ref('')
let checkValues = reactive(null)
let formData = reactive({})
let multiInstanceVars = ref('')
let vFormRef = ref(null)
onMounted(() => {
   load()
})

const load = () => {
  deployId.value = route.query && route.query.deployId;
  // 初始化表单
  procDefId.value = route.query && route.query.procDefId;
  // this.getNextFlowNodeByStart(this.deployId);
  getFlowFormData(deployId);
}

const getFlowFormData = (deployId: any) => {
  const params = {deployId: deployId.value}
  fetchData("/process/flowable/task/flowFormData", params).then(res => {
    // 流程过程中不存在初始化表单 直接读取的流程变量中存储的表单值
    formConf.value = res;
  }).catch(res => {
    goBack();
  })
}
const handleClick = (tab: any, event) => {
  if (tab.paneName === '2') {
    fetchData("/process/flowable/task/flowXmlAndNode", {deployId: deployId.value}).then(res => {
      flowData.value = res;
    })
  }
}
const goBack = () => {
  store.dispatch('tagsView/delRouterView', {
    "path":"/admin/task/process",
  })
  router.push("/admin/task/process")
}
const submitForm = () => {

  vFormRef.value.getFormData().then(submitdata => {//获取并校验表单数据
    saveorUpadateDate("/process/flowable/task/nextFlowNodeByStart", {
      deploymentId: deployId.value,
      variables: submitdata
    }).then((res: any) => {
      const data = res;
      if (data) {
        if (data.dataType === 'dynamic') {
          if (data.type === 'assignee') { // 指定人员
            checkSendUser.value = true;
            checkType.value = "single";
          } else if (data.type === 'candidateUsers') {  // 候选人员(多个)
            checkSendUser.value = true;
            checkType.value = "multiple";
          } else if (data.type === 'candidateGroups') { // 指定组(所属角色接收任务)
            checkSendRole.value = true;
          } else { // 会签
            // 流程设计指定的 elementVariable 作为会签人员列表
            multiInstanceVars = data.vars;
            checkSendUser.value = true;
            checkType.value = "multiple";
          }
          taskOpen.value = true
          taskTitle.value = "选择任务接收"
        } else {
          // Form Validation OK
          formData = reactive(submitdata)
          vFormRef.value.disableForm()
          let param = {
            "formJson": formConf.value
          }
          var list = Object.keys(formData);
          for (let i = 0; i < list.length; i++) {
            param[list[i]] = formData[list[i]]
          }
          if (procDefId.value) {
            // 启动流程并将表单数据加入流程变量
            saveorUpadateDate("/process/flowable/definition/start/" + procDefId.value, param).then(res => {
              ElMessage.success(res)
              goBack();
            })
          }
        }

      }
    })
  }).catch(error => {
    // Form Validation failed
    ElMessage.error(error)
  })
}
const submitTask = () => {
  if (!checkValues && checkSendUser) {
    ElMessage.error("请选择任务接收!")
    return;
  }
  if (checkValues && checkSendRole) {
    ElMessage.error("请选择流程接收角色组!")
    return;
  }
  if (formData) {
    const variables = this.formData.valData;
    const formData = this.formData.formData;
    // 表单是否禁用
    formData.disabled = true;
    // 是否显示按钮
    formData.formBtns = false;
    variables.variables = formData;
    // if (this.multiInstanceVars) {
    //   this.$set(variables, this.multiInstanceVars, this.checkValues);
    // } else {
    //   this.$set(variables, "approval", this.checkValues);
    // }
    console.log(variables, "流程发起提交表单数据")
    // 启动流程并将表单数据加入流程变量
    saveorUpadateDate("/flowable/definition/start/" + this.procDefId, JSON.stringify(variables)).then(res => {
      ElMessage.success(res)
      goBack();
    })
  }
}

</script>
<style lang="scss" scoped>
.test-form {
  margin: 15px auto;
  width: 800px;
  padding: 15px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.my-label {
  background: #E1F3D8;
}
</style>